package cn.rkylin.oms.common.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;

/**
 * 拦截器类处理整个系统用户的合法性
 */
public class MeasurementInterceptor implements HandlerInterceptor {

	/**
	 * 所有请求处理完成之后被调用 (前端页面展示之后)
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e)
			throws Exception {

	}

	/**
	 * 在程序请求处理之后被调用(允许返回ModelAndView对象，但是异步请,求返回的貌似无法获取ModelAndView对象)
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 登录检测
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		boolean forwardAction = true;
		CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
		if (null == currentUser) { // 校验接口异常或其他错误
			PrintWriter pw = response.getWriter();
			pw.print("<script>window.top.location.href='/login.html';</script>");
			forwardAction = false;
		} else {
			// TODO 判断一下用户是否有效，有效期？
			forwardAction = true;
		}
		return forwardAction;
	}

}
